<template>
  <div class="system-dic-container standard-container layout-padding layout-pd">
    <div class="review-list-title">
      <div class="title-actions">
        <el-button size="default" type="primary" class="ml10" @click="getTableData">
          <el-icon>
            <ele-Search/>
          </el-icon>
          查询
        </el-button>

        <el-button size="default" type="primary" class="ml10" @click="handleBatchDeleteDict">
          <el-icon>
            <ele-FolderAdd/>
          </el-icon>
          批量删除
        </el-button>
        <el-button size="default" type="success" class="ml10" @click="onOpenAddDict('add')">
          <el-icon>
            <ele-FolderAdd/>
          </el-icon>
          新增字典
        </el-button>
      </div>
    </div>
    <el-table :data="state.tableData.data" v-loading="state.tableData.loading" style="width: 100%"
              @selection-change="handleSelectionDict">
      <el-table-column type="selection" width="55"/>
      <el-table-column prop="title" label="字典标题" show-overflow-tooltip></el-table-column>
      <el-table-column prop="type" label="字典类型" show-overflow-tooltip></el-table-column>
      <el-table-column prop="category" label="字典分类" show-overflow-tooltip></el-table-column>
      <el-table-column prop="status" label="字典状态" show-overflow-tooltip>
        <template #default="scope">
          <el-tag type="success" v-if="scope.row.status == 1">启用</el-tag>
          <el-tag type="info" v-else>禁用</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间" show-overflow-tooltip></el-table-column>
      <el-table-column label="操作" width="100">
        <template #default="scope">
          <el-button size="small" text type="primary" @click="onOpenEditDic('edit', scope.row)">修改</el-button>
          <el-button size="small" text type="primary" @click="onRowDel(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="pagination-container">
      <el-pagination
          @size-change="onHandleSizeChange"
          @current-change="onHandleCurrentChange"
          :pager-count="5"
          :page-sizes="[10, 20, 30, 50, 100]"
          v-model:current-page="state.tableData.paging.currentPage"
          background
          v-model:page-size="state.tableData.paging.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="state.tableData.paging.totalCount"
      >
      </el-pagination>
    </div>
    <DictDialog ref="DictDialogRef" @refresh="getTableData()"/>
  </div>
</template>

<script setup lang="ts" name="systemDict">
import {defineAsyncComponent, reactive, onMounted, ref} from 'vue';
import {ElMessageBox, ElMessage} from 'element-plus';
import {dictApi} from '/@/api/sys/dict';
import msg from '/@/utils/messageUtils';
import {permissionApi} from "/@/api/sys/permission";
import messageUtils from "/@/utils/messageUtils";
// 引入组件
const DictDialog = defineAsyncComponent(() => import('/@/views/system/dict/dialog.vue'));
const DictDialogRef = ref();
// 定义变量内容
const state = reactive({
  search: '',
  choiceDictIds: [] as Array<string>,
  tableData: {
    data: [],
    total: 0,
    loading: false,
    paging: {
      currentPage: 1,
      pageSize: 15,
      totalCount: 0,
      totalPages: 0,
    },
  },
});

// 初始化表格数据
const getTableData = async () => {
  try {
    const {data} = await dictApi().pageSearch({
      offset: (state.tableData.paging.currentPage - 1) * state.tableData.paging.pageSize,
      limit: state.tableData.paging.pageSize,
    });
    state.tableData.data = data.datas;
    state.tableData.paging.currentPage = data.paging.currentPage;
    state.tableData.paging.totalCount = data.paging.totalCount;
  } catch (e) {
    msg().error('查询信息失败，请稍后重试');
  }
};
// 打开新增字典弹窗
const onOpenAddDict = (type: string) => {
  DictDialogRef.value.openDialog(type);
};
// 打开修改字典弹窗
const onOpenEditDic = (type: string, row: RowDictype) => {
  DictDialogRef.value.openDialog(type, row);
};
// 删除字典
const onRowDel = (row: RowDictype) => {
  ElMessageBox.confirm(`此操作将永久删除字典名称：“${row.title}”，是否继续?`, '提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning',
  })
      .then(async () => {
        await dictApi().remove(row.id);
        getTableData();
        ElMessage.success('删除成功');
      })
      .catch(() => {
      });
};


const handleBatchDeleteDict = () => {
  if (state.choiceDictIds.length == 0) {
    msg().warn('请至少选中一个');
    return;
  }
  ElMessageBox.confirm(`此操作将永久删除选中的字典，是否继续?`, '提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning',
  })
      .then(async () => {
        await dictApi().batchDelete({
          ids: state.choiceDictIds,
        });
        refresh();
        msg().success('删除成功....');
      })
      .catch((e) => {
        console.error(e);
        messageUtils().error("操作失败，稍后重试")
      });
};

const handleSelectionDict = (choiceIds: any) => {
  state.choiceDictIds = [];
  choiceIds.forEach((e: any) => state.choiceDictIds.push(e.id));
};
// 分页改变
// 分页改变
const onHandleSizeChange = (pageSize: number) => {
  state.tableData.paging.pageSize = pageSize;
  getTableData();
};
// 分页改变
const onHandleCurrentChange = (currentPage: number) => {
  state.tableData.paging.currentPage = currentPage;
  getTableData();
};

const refresh = () => {
  onHandleCurrentChange(1)
};
// 页面加载时
onMounted(() => {
  getTableData();
});
</script>

<style lang="scss" scoped>
.system-dic-container {
  padding: 15px;

  .el-table {
    flex: 1;
  }
}
</style>
